<template>
	<view class="page-container">
		<view class="content">
			<view class="complete">
				<view class="complete__top">
					<!-- 头像卡片轮播选择区域 -->
					<view class="avatar-swiper-container">
						<avaterSwiperVue ref="avatarSwiperRef" @avatar-change="handleAvatarUpdated" />
					</view>
				</view>

				<!-- 表单内容区域 -->
				<view class="complete__content">
					<!-- 昵称输入项 -->
					<view class="complete__content__items">
						<view class="complete__content__items__top">
							<image class="top_image" alt="image" :src="`${$ImgBaseUrl}nickname-icon.png`" />
							<text>昵称</text>
						</view>
						<view class="complete__content__items__bottom">
							<view class="bottomBox">
								<input class="input" v-model="nikeName" placeholder="请输入昵称"
									placeholder-style="color: #999999;" />
							</view>
						</view>
					</view>

					<!-- 性别选择项 -->
					<view class="complete__content__items">
						<view class="complete__content__items__top">
							<image class="top_image" alt="image" :src="`${$ImgBaseUrl}sex.png`" />
							<text>性别</text>
						</view>
						<view class="complete__content__items__bottom">
							<view class="bottomCon" :class="sex === 0 ? 'male_active' : ''" @click="changeSex(0)">
								<image class="bottom_image" alt="image"
									:src="sex === 0 ? `${$ImgBaseUrl}male_active.png` : `${$ImgBaseUrl}male.png`" />
								男
							</view>
							<view class="bottomCon" :class="sex === 1 ? 'female_active' : ''" @click="changeSex(1)">
								<image class="bottom_image" alt="image"
									:src="sex === 1 ? `${$ImgBaseUrl}female_active.png` : `${$ImgBaseUrl}female1.png`" />
								女
							</view>
						</view>
					</view>

					<!-- 年龄选择项 -->
					<view class="complete__content__items">
						<view class="complete__content__items__top">
							<image class="top_image" alt="image" :src="`${$ImgBaseUrl}age.png`" />
							<text>年龄</text>
						</view>
						<view class="complete__content__items__bottom">
							<view class="bottomBox">
								<picker class="picker" mode="date" :value="date" :start="startDate" :end="endDate"
									@change="bindDateChange">
									<view class="picker-content">
										<text v-if="age" class="age-text">{{ age }}岁</text>
										<text v-else class="placeholder">请选择出生日期</text>
									</view>
								</picker>
								<uni-icons type="right" size="12"></uni-icons>
							</view>
						</view>
					</view>

					<!-- 手机号输入项 -->
					<view class="complete__content__items">
						<view class="complete__content__items__top">
							<image class="top_image" alt="image" :src="`${$ImgBaseUrl}phone.png`" />
							<text>手机号</text>
						</view>
						<view class="complete__content__items__bottom">
							<view class="bottomBox">
								<input class="input" v-model="tel" type="number" maxlength="11" placeholder="请输入手机号"
									placeholder-style="color: #999999;" disabled="true" />
							</view>
						</view>
					</view>
				</view>

				<!-- 底部按钮区域 -->
				<view class="complete__btns">
					<text class="jump" @click="jump">跳过</text>
					<view class="next" @click="next">
						下一步
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		businessList,
		userBindBusiness,
		getGuideUser,
		userInfo
	} from '@/api/user.js'
	import {
		reactive,
		toRefs,
		onMounted,
		computed,
		ref,
		nextTick
	} from 'vue';
	import {
		ImgBaseUrl
	} from '@/utils/domain.js'
	import {
		useStore
	} from 'vuex';

	import avaterSwiperVue from './avater-swiper.vue';
	const store = useStore();
	const avatarSwiperRef = ref(null);
	const currentAvatar = ref(null);


	// 初始化响应式数据
	const state = reactive({
		date: '',
		sex: 0,
		tel: '',
		nikeName: '',
		startDate: '1900-01-01',
		endDate: new Date().toISOString().split('T')[0],
		birth: '',
		avatar: null, // 不再使用本地默认头像
		swiperOffset: 0,
	});

	// 解构响应式数据
	const {
		date,
		sex,
		tel,
		nikeName,
		startDate,
		endDate,
		birth,
		avatar,
		swiperOffset,
	} = toRefs(state);

	// 处理头像更新事件
	const handleAvatarUpdated = (data) => {
		currentAvatar.value = {
			tempPath: data.tempPath,
			baseUrl: data.baseUrl,
			index: data.index,
			isCustom: data.isCustom
		};
	};

	// 计算年龄的computed属性
	const age = computed(() => {
		if (!state.date) return '';

		const birthDate = new Date(state.date);
		const today = new Date();

		let age = today.getFullYear() - birthDate.getFullYear();
		const monthDiff = today.getMonth() - birthDate.getMonth();

		if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
			age--;
		}

		return age;
	});

	// 保存用户偏好设置
	const savePreferences = async () => {
		try {
			// 验证必填字段
			if (!state.nikeName) {
				throw new Error('请输入昵称');
			}
			if (!state.date) {
				throw new Error('请选择出生日期');
			}

			let finalAvatarUrl = '';

			// 上传头像并获取baseUrl
			if (currentAvatar.value) {
				uni.showLoading({
					title: '头像上传中...',
					mask: true
				});

				try {
					// 如果是自定义头像，可能需要上传
					if (currentAvatar.value.isCustom) {
						finalAvatarUrl = await avatarSwiperRef.value.uploadAvatar();
					} else {
						// 使用默认头像的baseUrl
						finalAvatarUrl = currentAvatar.value.baseUrl;
					}
				} catch (error) {
					console.error('头像处理失败:', error);
					throw new Error('头像处理失败，请重试');
				}
			} else {
				throw new Error('请选择头像');
			}

			const formData = {
				nikeName: state.nikeName,
				sex: state.sex,
				birth: state.date || state.birth,
				phone: state.tel,
				avatar: finalAvatarUrl // 使用baseUrl作为传给后台的值
			};

			// 调用API保存
			const res = await getGuideUser(formData);
			if (res.code === 200) {
				await getUserInfo(); // 等待用户信息更新

				uni.showToast({
					title: '保存成功',
					icon: 'success'
				});
				uni.redirectTo({
					url: "/pages/login/preferences"
				});
			} else {
				throw new Error(res.msg || '保存失败');
			}
		} catch (error) {
			console.error('保存失败:', error);
			uni.showToast({
				title: error.message || '保存失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};

	// 获取用户信息
	const getUserInfo = () => {
		return userInfo().then((info) => {
			if (info.code == 200) {
				store.commit('setUserInfo', info.data)
				uni.setStorageSync('user_info', JSON.stringify(info.data));

				// 同步更新当前页面头像
				if (info.data.avatar) {
					nextTick(() => {
						if (avatarSwiperRef.value?.updateCustomAvatar) {
							avatarSwiperRef.value.updateCustomAvatar(info.data.avatar);
						}
					});
				}
			} else {
				store.commit('clearLoginInfo')
			}
		});
	};

	// 性别切换
	const changeSex = (sexValue) => {
		state.sex = sexValue;
	}

	// 日期选择变化
	const bindDateChange = (e) => {
		state.date = e.detail.value;
		state.birth = e.detail.value;
	}

	// 跳过
	const jump = () => {
		uni.navigateTo({
			url: "/pages/login/preferences"
		});
	};

	// 下一步
	const next = () => {
		// 简单验证
		if (!state.nikeName) return uni.showToast({
			icon: 'none',
			title: '请输入昵称'
		});
		if (!state.date) return uni.showToast({
			icon: 'none',
			title: '请选择出生日期'
		});

		savePreferences();
	};

	// 页面挂载时获取缓存数据
	onMounted(() => {
		const userInfoStr = uni.getStorageSync('user_info');
		// console.log('userInfoStr', userInfoStr);

		if (userInfoStr.phone) state.tel = userInfoStr.phone;
		if (userInfoStr.nikeName) state.nikeName = userInfoStr.nikeName;
		if (userInfoStr.birth) {
			state.birth = userInfoStr.birth;
			state.date = userInfoStr.birth;
		}
		if (userInfoStr.sex !== undefined && userInfoStr.sex !== null) {
			state.sex = Number(userInfoStr.sex);
		}

		if (userInfoStr.avatar) {
			nextTick(() => {
				if (avatarSwiperRef.value?.updateCustomAvatar) {
					avatarSwiperRef.value.updateCustomAvatar(userInfoStr.avatar);
				}
			});
		}


	});
</script>

<style lang="less">
	/* 样式保持不变 */
	page,
	body {
		margin: 0;
		padding: 0;
		height: 100%;
		overflow: hidden;
	}

	.page-container {
		height: 100vh;
		overflow: hidden;
	}

	.content {
		height: 100%;
		overflow: hidden;
	}

	.complete {
		background: linear-gradient(180deg, #eef5ff 0%, #cae1ff 100%);
		height: 100%;
		display: flex;
		flex-direction: column;
		padding: 0 70rpx;

		&__top {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 30rpx 0;
		}

		.avatar-swiper-container {
			width: 100%;
			position: relative;
		}

		&__content {
			display: flex;
			flex-direction: column;
			justify-content: center;

			&__items {
				margin: 30rpx 0;

				&__top {
					display: flex;
					align-items: center;
					margin-bottom: 25rpx;

					.top_image {
						width: 40rpx;
						height: 40rpx;
						margin-right: 12rpx;
					}

					text {
						font-size: 32rpx;
						color: #333333;
						line-height: 40rpx;
						font-weight: 500;
					}
				}

				&__bottom {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.bottomCon {
						display: flex;
						align-items: center;
						justify-content: center;
						width: 45%;
						height: 96rpx;
						background: #ffffff;
						border-radius: 20rpx;
						font-size: 32rpx;
						color: #333333;
						line-height: 40rpx;

						.bottom_image {
							width: 28rpx;
							height: 28rpx;
							margin-right: 14rpx;
						}
					}

					.female_active {
						background: linear-gradient(90deg, #FF9D9D 0%, #FF5E5E 100%);
						color: #fff;
					}

					.male_active {
						background: linear-gradient(90deg, #9EC8FF 0%, #2F80ED 100%);
						color: #fff;
					}

					.bottomBox {
						width: 100%;
						display: flex;
						align-items: center;
						justify-content: space-between;
						height: 96rpx;
						padding: 0 27rpx;
						background: #ffffff;
						border-radius: 20rpx;

						.input {
							flex: 1;
							font-size: 28rpx;
							color: #333333;
							height: 100%;
							line-height: 85rpx;
						}
					}

					.picker {
						flex: 1;

						.picker-content {
							display: flex;
							align-items: center;
							height: 100%;
							font-size: 28rpx;

							.age-text {
								color: #333333;
							}
						}

						.placeholder {
							color: #999999;
						}
					}
				}
			}
		}

		&__btns {
			padding: 40rpx 0;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.jump {
				width: 140rpx;
				padding: 20rpx 0;
				font-size: 28rpx;
				color: #2F80ED;
				line-height: 38rpx;
				text-align: center;
				border-radius: 44rpx;
				border: 1px solid #2F80ED;
				margin-right: 24rpx;
			}

			.next {
				flex: 1;
				padding: 20rpx 0;
				background: #2F80ED;
				border-radius: 44rpx;
				font-weight: 600;
				font-size: 28rpx;
				color: #FFFFFF;
				line-height: 38rpx;
				text-align: center;
			}
		}
	}
</style>